package 临时工具.其他;

import com.sun.management.OperatingSystemMXBean;

import java.io.IOException;
import java.lang.management.ManagementFactory;

public class CpuMonitor {

    public static void main(String[] args) {
        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

        while (true) {
            try {
                double cpuLoad = osBean.getSystemCpuLoad(); // 返回值在 0.0 ~ 1.0
                if (cpuLoad >= 0) {
                    double cpuPercent = cpuLoad * 100;
                    System.out.printf("当前 CPU 占用率: %.2f%%%n", cpuPercent);

                    if (cpuPercent > 80.0) {
                        System.out.println("CPU 超过 80%，正在终止 ffmpeg 进程...");
                        killFfmpeg();
                    }
                } else {
                    System.out.println("等待 CPU 采样数据...");
                }

                Thread.sleep(10000); // 10秒钟检查一次

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }

    private static void killFfmpeg() {
        ProcessBuilder pb = new ProcessBuilder()
                .command("cmd.exe", "/c", "taskkill /f /t /im ffmpeg.exe");

        try {
            Process process = pb.start();
            process.waitFor(); // 等待命令执行完毕（可选）
            System.out.println("ffmpeg 已终止。");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
